import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';
import { 
  login, loginByUkey, loginByMsg, loginBySsoCode, loginBySsoToken, 
  loginBySsoClientIp, loginBySsoClientId, loginBySso, 
  goBacklogBySecretKey, logoutBySsoCode 
} from '../api/login';
import { 
  getDbsxNum, getEmailList, getHtglNum, getNetWorkNum, getGxglNum 
} from '../api/module/grbg/todoList';
import { getSetting } from '../api/common/notion';
import { zddk } from '../api/module/kqgl/kqgl';
import { getToken, setToken, removeToken, setSSOToken, removeSSOToken, getSSOToken } from '../utils/auth';
import websocket from '../utils/websocket';
// import BlogMessage from '../components/Message/index';
import { getCs } from '../api/system/csgl/cszc';
// import { EventBus } from '../components/HCEventBus/eventBus';

export const useAuthStore = defineStore('auth', () => {
  // 状态（替代 Vuex 的 state）
  const token = ref(getToken());
  const currentPostUnid = ref(null);
  const roles = ref([]);
  const info = ref({});
  const totalBacklogCount = ref(0);
  const lastNetMessageCom = ref(null);
  const totalYbsxCount = ref(0);
  const totalEmaillogCount = ref(0);
  const totalNetMessageCount = ref(0);
  const currentOrgUnid = ref(null);
  const ywyjxgSetting = ref({});
  let timgerId = null;

  // 获取器（替代 Vuex 的 getters）
  const isAuthenticated = computed(() => !!token.value);

  // 动作（替代 Vuex 的 actions）
  const setTokenAction = (newToken) => {
    if (newToken) {
      setToken(newToken);
      token.value = newToken;
    } else {
      removeToken();
      token.value = null;
    }
  };

  const setCurrentPost = (postUnid) => {
    if (postUnid) {
      currentPostUnid.value = postUnid;
      localStorage.setItem(`postUnid_${info.value.unid}`, postUnid);
    } else {
      currentPostUnid.value = null;
      localStorage.removeItem(`postUnid_${info.value.unid}`);
    }
  };

  const setRoles = (newRoles) => {
    roles.value = newRoles;
  };

  const setInfo = (newInfo) => {
    if (newInfo) {
      localStorage.setItem('info', JSON.stringify(newInfo));
      info.value = newInfo;
    } else {
      localStorage.removeItem('info');
      info.value = null;
    }
  };

  const setEmailNum = (count) => {
    totalEmaillogCount.value = count || 0;
  };

  const setNetMessageNum = (count) => {
    totalNetMessageCount.value = count || 0;
  };

  const setLastNetMessageCom = (com) => {
    lastNetMessageCom.value = com;
  };

  const setDbsxNum = (count) => {
    totalBacklogCount.value = count || 0;
  };

  const setYbsxNum = (value) => {
    totalYbsxCount.value = value || 0;
  };

  const setAvatar = (value) => {
    info.value.avatar = value;
  };

  const setCurrentOrgUnid = (value) => {
    if (value) {
      currentOrgUnid.value = value;
      localStorage.setItem(`orgUnid_${info.value.unid}`, value);
    } else {
      currentOrgUnid.value = null;
      localStorage.removeItem(`orgUnid_${info.value.unid}`);
    }
  };

  const setYwyjxgSetting = (value) => {
    ywyjxgSetting.value = value;
  };

  // 登录相关方法
  const loginAction = async (userInfo) => {
    try {
      const res = await login(userInfo);
      setTokenAction(res.token);
      return res;
    } catch (error) {
      throw error;
    }
  };

  const loginByMsgAction = async (userInfo) => {
    try {
      const res = await loginByMsg(userInfo);
      setTokenAction(res.token);
      return res;
    } catch (error) {
      throw error;
    }
  };

  const loginByUkeyAction = async (data) => {
    try {
      const res = await loginByUkey(data);
      setTokenAction(res.token);
      return res;
    } catch (error) {
      throw error;
    }
  };

  const loginByCodeAction = async (data) => {
    try {
      const response = await loginBySsoCode(data);
      setTokenAction(response.token || response.data.token);
      setSSOToken(response.access_token || response.data.access_token);
      return response;
    } catch (error) {
      throw error;
    }
  };

  const loginByTokenAction = async (data) => {
    try {
      const response = await loginBySsoToken(data);
      setTokenAction(response.token || response.data.token);
      setSSOToken(response.access_token || response.data.access_token);
      return response;
    } catch (error) {
      throw error;
    }
  };

  const loginByClientIpAction = async (data) => {
    try {
      const response = await loginBySsoClientIp(data);
      setTokenAction(response.token || response.data.token);
      setSSOToken(response.access_token || response.data.access_token);
      return response;
    } catch (error) {
      throw error;
    }
  };

  const loginByClientIdAction = async (data) => {
    try {
      const response = await loginBySsoClientId(data);
      setTokenAction(response.token || response.data.token);
      setSSOToken(response.access_token || response.data.access_token);
      return response;
    } catch (error) {
      throw error;
    }
  };

  const hzLoginByPasswordAction = async (data) => {
    try {
      const res = await getCs("xtsz_decode_password");
      let isBtoaPassWord = false;
      if (res.result && res.result.defauleValues == 1) {
        isBtoaPassWord = true;
      }
      const loginData = {
        username: data.username,
        password: isBtoaPassWord ? window.btoa(data.password) : data.password
      };
      return loginAction(loginData);
    } catch (error) {
      throw error;
    }
  };

  const loginBySSOAction = async (data) => {
    try {
      const response = await loginBySso(data);
      setTokenAction(response.token);
      return response;
    } catch (error) {
      throw error;
    }
  };

  const goBacklogBySecretKeyAction = async (data, params) => {
    try {
      const response = await goBacklogBySecretKey(data);
      setTokenAction(response.token);
      // 注意：这里需要访问 router，但 Pinia store 中无法直接访问
      // 实际项目中应通过其他方式实现路由跳转
      console.log('跳转参数:', params);
      return response;
    } catch (error) {
      throw error;
    }
  };

  // 更新各类消息数量
  const updateGxrz = () => {
    getGxglNum().then(res => {
      console.log(res, '更新内容');
      if (res.result) {
        BlogMessage({
          msg: `更新内容: ${res.result.remark}`,
          title: "更新提示",
          event: null,
          url: "/gxgl/gxglck",
          gxjlunid: res.result.unid
        });
      }
    });
  };

  const updateHtglNum = () => {
    getHtglNum().then(res => {
      let isHtts = localStorage.getItem('isHtts') || false;
      if (!isHtts) {
        isHtts = true;
        localStorage.setItem('isHtts', isHtts);
        if (res.result) {
          Object.keys(res.result).forEach(key => {
            if (key === info.value.unid) {
              BlogMessage({
                msg: `您有${res.result[key]}条合同需要线下归档，请及时处理`,
                title: "消息提醒",
                event: null,
                url: ""
              });
            }
          });
        }
      }
    });
  };

  const updateDbsxNum = (showMessage = true) => {
    getDbsxNum().then((res) => {
      let isTs = localStorage.getItem('isTs') || false;
      setDbsxNum(res.result.dbsl);
      if (!isTs && window.HC_config.VUE_APP_BACKLOGTIP) {
        isTs = true;
        localStorage.setItem('isTs', isTs);
        if (res.result.dbsl > 1 && showMessage) {
          BlogMessage({
            msg: `您有${res.result.dbsl}条待办消息，请注意查收`,
            title: "消息提醒",
            event: null,
            url: "/dbsxgl/dbsx"
          });
        }
      }
      setYbsxNum(res.result.ybsl);
    });
  };

  const updateEmailNum = () => {
    getEmailList().then(({ result }) => {
      result && setEmailNum(result.count);
    });
  };

  // 获取用户信息
  const getInfo = async () => {
    // 开启websock消息实时获取功能
    if (window.HC_config && window.HC_config.VUE_OPEN_WEBSOCKET) {
      websocket.closeWebSocket();
      websocket.initWebSocket(token.value, (obj) => {
        // 处理待办消息
        if (obj.type === "cldb") {
          updateDbsxNum(false);
          // 触发实时刷新待办数据
          EventBus.$emit("refreshBacklog");
          return;
        }
        // 刷新邮件消息条数
        if (obj.type === 'clyj') {
          updateEmailNum();
          return;
        }
        if (obj.type === 'znxx') {
          // 获取用户的站内消息
          getNetWorkNum().then(({ result }) => {
            let netMessageNum = result || 0;
            setNetMessageNum(netMessageNum);
          });
          return;
        }
        let url = obj.url;
        if (obj.toFromUnid != null && url != null) {
          if (obj.url.indexOf("?") > -1) {
            url = url + "&unid=" + obj.toFromUnid;
          } else {
            url = url + "?unid=" + obj.toFromUnid;
          }
        }
        // 获取用户的站内消息
        getNetWorkNum().then(({ result }) => {
          let netMessageNum = result || 0;
          setNetMessageNum(netMessageNum);
        });

        BlogMessage({
          msg: obj.content,
          title: "消息提醒",
          event: obj.moduleEvent,
          url: url,
          logUnid: obj.logUnid
        });
      });

      // 获取用户的站内消息
      getNetWorkNum().then(({ result }) => {
        let netMessageNum = result || 0;
        setNetMessageNum(netMessageNum);
      });
    }

    // 获取当前登录人的代表事项
    if (window.HC_config.VUE_APP_isShowDBSX || window.HC_config.VUE_APP_isShowYBSX) {
      // 每10秒获取一次代表事项
      startTimer(() => {
        updateDbsxNum(true);
      });
    }

    // 获取当前登录人的未读邮件
    if (window.HC_config.VUE_APP_isShowEmail) {
      getEmailList({}).then(({ result }) => {
        result && setEmailNum(result.count);
      });
    }

    // 获取阅文意见修改设置
    if (window.HC_config.VUE_APP_isShowYwOpinion) {
      getSetting().then(res => {
        setYwyjxgSetting(res.result || {});
      });
    }

    try {
      const response = await getInfo();
      setInfo(response.result);
      setRoles(response.result.roleKey);
      // 是否登录成功自动打卡
      if (window.HC_config.VUE_USE_ZDDK) {
        const par = {
          personId: response.result.unid,
          personName: response.result.personCommonname
        };
        zddk(par);
      }
      // 获取当前登录人需处理合同文件
      if (window.HC_config.VUE_APP_isShowHtgl) {
        updateHtglNum();
      }
      if (window.HC_config.VUE_APP_isShowGxrz) {
        updateGxrz();
      }
      // 根据unid查询缓存，如果存在则使用缓存，不存在使用用户的
      const currentPostUnid = localStorage.getItem(`postUnid_${info.value.unid}`);
      if (currentPostUnid != null) {
        setCurrentPost(currentPostUnid);
      }

      return response;
    } catch (error) {
      throw error;
    }
  };

  // 登出
  const logOut = async () => {
    try {
      setTokenAction(null);
      setInfo(null);
      setCurrentOrgUnid(null);
      setCurrentPost(null);
      // 退出登录关闭websocket
      if (window.HC_config.VUE_OPEN_WEBSOCKET) {
        websocket.closeWebSocket();
      }
      // 退出判断是否是单点登录进来的，若是则通知认证系统也退出
      const ssoToken = getSSOToken();
      console.log(ssoToken, "================单点登录退出==================");
      if (window.HC_config.VUE_IS_SSO && window.HC_config.VUE_APP_SSO_LOGOUT_NOTIFY && ssoToken) {
        await logoutBySsoCode({ access_token: ssoToken });
        console.log("================单点登录退出成功==================");
        removeSSOToken();
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 前端登出
  const fedLogOut = () => {
    setTokenAction(null);
    setInfo(null);
    // 退出登录关闭websocket
    if (window.HC_config.VUE_OPEN_WEBSOCKET) {
      websocket.closeWebSocket();
    }
  };

  // 定时器辅助函数
  const startTimer = (callBack) => {
    clearInterval(timgerId);
    callBack();
    timgerId = setInterval(() => {
      callBack();
    }, 60000);
  };

  // 监听 token 变化，token 失效时自动登出
  watch(token, (newToken) => {
    if (!newToken) {
      setInfo(null);
      setRoles([]);
    }
  });

  return {
    // 状态
    token,
    currentPostUnid,
    roles,
    info,
    totalBacklogCount,
    lastNetMessageCom,
    totalYbsxCount,
    totalEmaillogCount,
    totalNetMessageCount,
    currentOrgUnid,
    ywyjxgSetting,
    
    // 获取器
    isAuthenticated,
    
    // 动作
    loginAction,
    loginByMsgAction,
    loginByUkeyAction,
    loginByCodeAction,
    loginByTokenAction,
    loginByClientIpAction,
    loginByClientIdAction,
    hzLoginByPasswordAction,
    loginBySSOAction,
    goBacklogBySecretKeyAction,
    updateGxrz,
    updateHtglNum,
    updateDbsxNum,
    updateEmailNum,
    getInfo,
    logOut,
    fedLogOut,
    
    // 内部方法
    setTokenAction,
    setCurrentPost,
    setRoles,
    setInfo,
    setEmailNum,
    setNetMessageNum,
    setLastNetMessageCom,
    setDbsxNum,
    setYbsxNum,
    setAvatar,
    setCurrentOrgUnid,
    setYwyjxgSetting,
    startTimer
  };
});